const data = require('./data.json')
const fs = require('fs')
const path = require('path')
// 自增图书序号
let bookCode = () => {
  let arr = []
  data.forEach(item => {
    arr.push(item.id)
  })
  return Math.max.apply(null, arr)
}
// 文件写入
let writeBook = (res) => {
  fs.writeFile(path.join(__dirname, 'data.json'), JSON.stringify(data, null, 4),(err) => {
    if(!err) {
      res.json({
        status: 200
      })
    }else {
      res.json({
        status: 500
      })
    }

  })
}
// 获取图书列表
exports.getAllBook  = (req,res) => {
  res.json(data)
}
// 提交图书
exports.addBook = (req,res) => {
  let info = req.body
  let book = {}
  for(key in info) {
    book[key] = info[key]
  }
  book.date = new Date()
  book.id = bookCode() + 1
  data.push(book)
  writeBook(res)
}
// 修改图书
exports.editBook = (req,res) => {
  let info = req.body
  let id = req.params.id
  data.forEach(item => {
    if(item.id == id) {
      item.name = info.name
      item.date = new Date()
    }
  })
  writeBook(res)
}
// 删除图书
exports.deleteBook = (req,res) => {
  let id = req.params.id
  data.some((item,index) => {
    if (item.id == id) {
      data.splice(index,1)
    }
  })
  writeBook(res)
}
// 验证图书的存在
exports.checkName = (req,res) => {
  let name = req.params.name
  let flag
  data.some(item => {
    if(name == item.name) {
      flag = true
      return true
    }
  })
  if(flag) {
    res.json({
      status: 1
    })
  }else {
    res.json({
      status: 2
    })
  }
}